package com.example.polardbxdemo.rust;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

import java.net.URI;
import java.nio.file.Paths;

public class RustfsS3Example {

    public static void main(String[] args) {
        // 1. 初始化 S3 客户端
        S3Client s3 = S3Client.builder()
                .endpointOverride(URI.create("http://39.101.169.161:9100")) // RustFS 地址
                .region(Region.US_EAST_1) // 可写死，RustFS 不校验 region
                .credentialsProvider(
                        StaticCredentialsProvider.create(
                                AwsBasicCredentials.create("rustfsadmin", "rustfsadmin")
                        )
                )
                .forcePathStyle(true) // 关键配置！RustFS 需启用 Path-Style
                .build();

        // 2. 创建 Bucket
        String bucket = "my-bucket";
        try {
            s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
            System.out.println("Bucket created: " + bucket);
        } catch (BucketAlreadyExistsException | BucketAlreadyOwnedByYouException e) {
            System.out.println("Bucket already exists.");
        }

        // 3. 上传文件
        s3.putObject(
                PutObjectRequest.builder().bucket(bucket).key("hello.txt").build(),
                Paths.get("C:\\Users\\20923\\Desktop\\work\\helloZjx.txt")
        );
        System.out.println("Uploaded hello.txt");

        // 4. 下载文件
        s3.getObject(
                GetObjectRequest.builder().bucket(bucket).key("hello.txt").build(),
                Paths.get("C:\\Users\\20923\\Desktop\\work\\downloaded-hello.txt")
        );
        System.out.println("Downloaded hello.txt");

        // 5. 列出对象
        ListObjectsV2Response listResponse = s3.listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build());
        listResponse.contents().forEach(obj -> System.out.println("Found object: " + obj.key()));

        // 6. 删除对象
//        s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key("hello.txt").build());
//        System.out.println("Deleted hello.txt");

        // 7. 删除桶（可选）
        // s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build());
    }
}